import React, { useContext, useState } from "react";
import { AuthContext } from "../App";

const Login = () => {

    const { dispatch } = useContext(AuthContext);
    const initialState = {
        email: "",
        password: "",
        // ?
        isSubmitting: false,
        errorMessage: null
    }
    // 表单有内部的状态
    const [data, setData] = useState(initialState)

    const handleInputChange = (event) => {
        setData({
            ...data,
            [event.target.name]: event.target.value
        })
    }

    const handleFormSubmit = event => {
        event.preventDefault();
        setData({
            ...data,
            isSubmitting: true,
            errorMessage: null
        })
        // 远程请求mock
        fetch("https://www.fastmock.site/mock/4f8c468ae7202f91850147535d932340/sbt/ali/login",
        // 请求头
        {
            method:'post',
            headers: {
            // 按照JSON格式处理它
                "Content-Type":'application/json'
            },
            // 请求体，变成字符串
            body:JSON.stringify({
                email:data.email,
                password:data.password
            })
        })
        .then(res=>res.json())
        .then(resJSON => {
            console.log(resJSON);
        })
    }

    return (
        <div className="login-container">
            <div className="card">
                <div className="container">
                    <form onSubmit={handleFormSubmit}>
                        <h1>Login</h1>
                        <label htmlFor="email">Eamil Address
                        <input 
                            type="email" 
                            value={data.email} 
                            onChange={handleInputChange}
                            id="email" 
                            name="email" />
                        </label>
                        <label htmlFor="password">Password
                        <input 
                            type="password" 
                            value={data.password} 
                            onChange={handleInputChange}
                            id="password" 
                            name="password" />
                        </label>
                        {data.errorMessage && (
                            <span className="form-error">{data.errorMessage}</span>
                        )}
                        <button disabled={data.isSubmitting} type="submit">Login</button>
                    </form>
                </div>
            </div>
        </div>
    )
}
export default Login